<?php

namespace Lib\Core;

use Lib\Util\Comm as Comm;

class Url extends \Home{

    /**
     * @param array $defaultPath
     * @param       $route
     *
     * @return @return \Lib\Core\Controller
     * @throws \Lib\Exception\Business
     */
    public function getController($defaultPath = array('Index', 'Index'), $route = null) {
        $result = Comm::getUrlPath($route);
        $path = $result['path'];
        if ($path && $path[0] == 'Ajax') {
            return $this->getAjaxController($path);
        }
        if (!$path) {
            $path = $defaultPath;
        }
        if (count($path) == 1) {
            $path[] = 'Index';
        }
        $class = 'Controller\\';
        $class .= implode('\\', $path);
        if (!preg_match('/^[\w\\\]+$/', $class)) {
            throw new \Lib\Exception\Controller('请求路径错误');
        }
        $obj = $class::instance();
        $match = $result['match'];
        if ($match) {
            $obj->setRouteParams($match);
        }
        return $obj;
    }

	public function getApiController() {
		$result = Comm::getUrlPath();
		$path = $result['path'];
		if (count($path) != 2) {
			throw new \Lib\Exception\Business('bad url request');
		}
		$function = array_pop($path);
		$class = 'Controller\\';
		$class .= implode('\\', $path);
		return $class::instance()->setFunction($function);
	}

    private function getAjaxController($path) {
        if (count($path) != 3) {
            throw new \Lib\Exception\Business('bad url request');
        }
        $function = array_pop($path);
        $class = 'Controller\\';
        $class .= implode('\\', $path);
        return $class::instance()->setFunction($function);
    }
}
